//是否保存学习流水
var playRecordFlow =false;
// 视频素材id
var materialId=0;
/**
 * 加载播放器
 * @param sign 播放数据签名
 */
function loadPlayData(sign) {
    $.ajax({
        url:baseloaction +'/web/uc/play/loadPlayData',
        type:'post',
        dataType:'json',
        data:{
            'sign':sign
        },
        success:function (result) {
            if(result.success==true){
                var catalog = result.entity;
                var playerUrl = result.player;
                var isK96keVideo = result.isK96keVideo;
                playRecordFlow =true;
                materialId=catalog.materialId;
                play(catalog,playerUrl,isK96keVideo);
            }else{
                icModale(0,'',result.message);
            }
        },
        error:function (error) {
            icModale(0,'','系统错误，加载播放数据失败');
        }
    });
}
/**
 * 执行播放
 * @param catalog 目录对象数据
 */
function play(catalog,playerUrl,isK96keVideo) {
    //清空定时器
    closeTiming();
    //资源对象
    var material = catalog.material;
    //得到播放记录
    playRecord = catalog.coursePlayRecord;
    $("#materialTypeKey").val(material.typeKey);
    if(material.typeKey=='VIDEO' || material.typeKey=='AUDIO'){//视频 音频
        var script = '';
        if(material.playType=='96K' || isK96keVideo) {
            script = playerUrl + '?width=100%&height=100%&videoId=' + material.playUrl;
            $("#play-video-live-box").html('<script src="' + script + '"></script>');
        }
        $("#play-video-live-box").removeClass("hide");
        $(".play-article__wrap").addClass("hide");
        videoAudioStudyTiming = setInterval(function () {
            studyTime ++;
        },1000);
    }else if(material.typeKey=='LIVE'){//直播
        var liveContext = '<iframe id="Iframe" name="Iframe1" width="100%" allowfullscreen frameborder="0"   allow="microphone; camera" height="100%" src="'+playerUrl+'"></iframe>';
        $("#play-video-live-box").html(liveContext);
        liveStudyTiming = setInterval(function () {
            studyTime ++;
        },1000);
    }else if(material.typeKey=='ARTICLE'){//文章
        //隐藏视频播放区
        $("#play-video-live-box").addClass("hide");
        //清空视频播放区
        $("#play-video-live-box").html('');
        //显示文章内容区
        $(".play-article__wrap").removeClass("hide");
        //显示文章内容
        $("#article_container").html(material.articleContext);
        articleStudyTiming = setInterval(function () {
            studyTime ++;
        },1000);
    }else{
        icModale(0,'','节点数据错误，播放失败');
    }
}

//======================96k开始======================
//播放的时长（单位/秒）
var studyTime = 0;
var total_duration =0;
var isCherkDuration=false;

//播放创建完成回调
function ke96_onPlayerInitOver() {
    console.log("---播放器数据初始化完毕---");
    //当前正在播放的目录ID
    var playId = $("#playId").val();
    //当前播放的课程ID
    var courseId = $("#courseId").val();
    var duration = $("input[data-duration=" +courseId+"-" +playId+"]").val();
    if(duration){
        ke96seekByJs(duration);
    }else{
        ke96seekByJs(0)
    }

}

//播放器类型回调
function ke96_VideoPlayerType(object){
    currentPlayType = object.type;
    currentVideoId = object.videoId;
}

/**
 * 设置视频起始播放
 */
function ke96seekByJs(time) {
    console.log("---------time----------"+time)
    var videoId = getVideoId();
    var obj = thisMovie(videoId);
    if(typeof obj !='undefined'){
        obj.ke96_seekByJs(time);
    }else{
        kooMobileH5.kooSeek(time);
    }
}

/**
 * 播放中监听
 * @param obj 视频信息
 */
function ke96_VideoState(obj) {
    // 试听 时长限制
    studyTime = obj.playTime;
    total_duration = obj.total_duration;
    isCherkDuration=true;
}


/**
 * 播放完成回调
 */
function ke96_onPlayOver(){
    //保存学习记录
    saveCourseLearnFlow(2);
    //视频、音频播放完成，清空所有定时器
    closeTiming();
}

/**
 *停止播放
 */
function stopPlay() {
    var videoId = getVideoId();
    var obj = thisMovie(videoId);
    if(typeof obj !='undefined'){
        obj.ke96_pauseByJs();
    }
}

/**
 * 获取视频的ID
 * @return {jQuery}
 */
function getVideoId() {
    var videoId = $("#play-video-live-box>object").attr('id');
    return videoId;
}

/**
 * 得到当前播放的视频
 * @param movieName
 * @return {*}
 */
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
//======================96k结束======================

//======================CC开始=======================
var vPlayer = null;
window.on_cc_player_init = function (vid,objId) { //该方法flash会在加载完成后主动调用
    vPlayer = getSWF(objId);//要在回调之后赋值
    var config={};//配置信息
    config.on_player_stop = "ccPlayerStop";//播放结束回调
    config.on_player_start = "ccPlayerStart";//开始播放时回调

    vPlayer.setConfig(config);//设置配置信息接口;
    vPlayer.start(); //开始播放（要在on_cc_player_init方法被调用之后执行,其他方法同理）
};

/**
 * CC播放结束回调
 */
function ccPlayerStop() {
    studyTime = vPlayer.getPosition();
    //完成播放保存学习记录
    saveCourseLearnFlow(2);
    //视频、音频播放完成，清空所有定时器
    closeTiming();
}

/**
 * flash对象
 * @param swfID
 * @returns {*}
 */
function getSWF( swfID ) {
    if (window.document[ swfID ]) {
        return window.document[ swfID ];
    } else if (navigator.appName.indexOf("Microsoft") == -1) {
        if (document.embeds && document.embeds[ swfID ]) {
            return document.embeds[ swfID ];
        }
    } else {
        return document.getElementById( swfID );
    }
}
//======================CC结束=======================

//======================保利，开始===================
var polyvObj= null;
// 	播放器数据初始化完毕后，会尝试调用此javascript函数
function s2j_onPlayerInitOver() {
}
/**
 * 视频播放结束后，会调用此函数
 */
function s2j_onPlayOver() {
    studyTime = polyvObj.j2s_realPlayVideoTime();
    //保存学习记录
    saveCourseLearnFlow(2);
    //视频、音频播放完成，清空所有定时器
    closeTiming();
}
//======================保利，结束===================

//文章定时器
var articleTiming = null;
//视频、音频定时器
var videoAudioTiming = null;
//文章学习定时器
var articleStudyTiming = null;
//直播学习定时器
var liveStudyTiming = null;
//视频、音频学习定时器
var videoAudioStudyTiming = null;
/**
 * 清空定时器
 */
function closeTiming() {
    studyTime = 0;
    if(articleTiming !=null){
        window.clearInterval(articleTiming);
        articleTiming = null;
    }
    if(videoAudioTiming !=null){
        window.clearTimeout(videoAudioTiming);
        videoAudioTiming = null;
    }
    if(liveStudyTiming !=null){
        window.clearInterval(liveStudyTiming);
        liveStudyTiming = null;
    }
    if(articleStudyTiming !=null){
        window.clearInterval(articleStudyTiming);
        articleStudyTiming = null;
    }
    if(videoAudioStudyTiming !=null){
        window.clearInterval(videoAudioStudyTiming);
        videoAudioStudyTiming = null;
    }
}

window.addEventListener('pagehide', function () {
    $.ajaxSettings.async = false;
    saveCourseLearnFlow(1);

});

window.onunload = function () {

    saveCourseLearnFlow(1);
}
//保存课程学习流水
function saveCourseLearnFlow(finish){
    if(playRecordFlow){
        //当前正在播放的目录ID
        var playId = $("#playId").val();
        //课程/套餐ID(购买的课程ID)
        var buyCourseId = $("#buyCourseId").val();
        //当前播放的课程ID
        var courseId = $("#courseId").val();
        var materialTypeKey = $("#materialTypeKey").val();
        if(materialTypeKey=="LIVE" || materialTypeKey=="ARTICLE"){
            if (studyTime >= 30) {
                finish=2;
            }else{
                return;
            }
        }
        if(isCherkDuration){
            if(studyTime>total_duration){
                studyTime=total_duration;
            }
        }
        if (!(studyTime >= 30)&&finish==1) {
            return;
        }
        var params = {
            'buyCourseId':buyCourseId,
            'courseId':courseId,
            'catalogId':playId,
            'duration':studyTime,
            'materialTypeKey':materialTypeKey,
            'finish':finish,
            'materialId':materialId
        };
        params = JSON.stringify(params);
        $.ajax({
            url:baseloaction +'/web/uc/course/play/Flow/savePlayRecordFlow',
            type:'post',
            dataType:'json',
            data:params,
            async:false,
            contentType: 'application/json;charset=utf-8'
        });
        playRecordFlow =false;
        isCherkDuration=false;
        closeTiming();
    }
}